<template>
  <div
    :style="`width: ${width.toString().includes('%') ? width : width + 'px'}`"
  >
    <el-input
      ref="inputRef"
      placeholder="请点击选择"
      v-model="materialName"
      :multiple="isMultiple"
      :style="`width: ${width.toString().includes('%') ? width : width + 'px'}`"
      :disabled="isDisabled"
      clearable
      @click="handleInputFocus"
      @clear.stop="handleInputClear"
      @input="handleInput"
    >
      <template #append>
        <el-button
          ref="matarialSelectButtonRef"
          :icon="Search"
          :disabled="isDisabled"
          @click="openMaterialDialog"
          >选择</el-button
        >
      </template>
    </el-input>
    <SelectMaterialDialog
      v-model:visible="materialSelect.visible"
      :data="materialSelect.data"
      :isMultiple="isMultiple"
      @echo-info="getMaterialSelect"
    />
  </div>
</template>

<script setup lang="ts">
import { ElInput, ElButton } from "element-plus";
import { Search } from "@element-plus/icons-vue";
defineOptions({
  name: "SELECTMATERIAL",
  inheritAttrs: false,
});

const emit = defineEmits(["get-material", "clear-material"]);

const props = defineProps({
  isMultiple: {
    type: Boolean,
    default: false,
  },
  width: {
    type: [String, Number],
    default: 200,
  },
  isDisabled: {
    type: Boolean,
    default: false,
  },
});

const { width, isMultiple, isDisabled } = toRefs(props);

/** 打开物料选择器方法   start **/
interface SelectOption {
  id?: string;
}
const materialName: any = ref("");
const materialDatas: any = ref([]); // 选择器 mode
const materialOptions: any = ref([]); // 选择器 list
const inputRef = ref(ElInput); // 选择器 ref
const matarialSelectButtonRef = ref(ElButton);
// 定义 物料选择器弹窗参数
const materialSelect = reactive<DialogOption>({
  visible: false,
  data: [],
});

function handleInputFocus() {
  materialSelect.visible = true;
  materialSelect.data = materialOptions.value;
}

// 打开 物料选择器弹窗
function openMaterialDialog() {
  materialSelect.visible = true;
  materialSelect.data = materialOptions.value;
}

function handleInputClear() {
  inputRef.value.blur();
  materialName.value = "";
  materialDatas.value = [];
  materialOptions.value = [];
  emit("clear-material");
}

function handleInput() {
  inputRef.value.blur();
  materialSelect.visible = true;
  materialSelect.data = materialOptions.value;
  materialName.value =
    materialOptions.value.length > 0
      ? materialOptions.value[0].materialName
      : "";
}

// 接收 物料选择器回调参数
function getMaterialSelect(options: any) {
  materialOptions.value = options;
  const ids: any = [];
  options?.map((item: SelectOption) => ids.push(item.id));
  materialDatas.value = ids || [];
  materialName.value = materialOptions.value[0].materialName;
  emit("get-material", materialDatas.value, materialOptions.value);
}

/** 打开物料选择器方法 **/
watch({ deep: true, immediate: true });

onMounted(() => {});
</script>
